<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="盘点年份" prop="year">
        <el-input
          v-model="queryParams.year"
          placeholder="请输入盘点年份"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点月份" prop="month">
        <el-select v-model="queryParams.month" placeholder="请选择盘点月份" clearable>
          <el-option
            v-for="dict in shop_inventory_month"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品" prop="month">
        <el-select v-model="queryParams.fid" placeholder="请选择商品" clearable >
          <el-option
              v-for="item in  fGroup"
              :key="item.fid"
              :label="item.food"
              :value="item.fid"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['shop:monthIncome:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['shop:monthIncome:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['shop:monthIncome:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['shop:monthIncome:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="monthIncomeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="盘点年份" align="center" prop="year" />
      <el-table-column label="盘点月份" align="center" prop="month">
        <template #default="scope">
          <dict-tag :options="shop_inventory_month" :value="scope.row.month"/>
        </template>
      </el-table-column>
      <el-table-column label="商品名" align="center" prop="foodName" />
      <el-table-column label="本月开销" align="center" prop="purchaseIncome" />
      <el-table-column label="本月收入" align="center" prop="sellIncome" />
      <el-table-column label="本月利润" align="center" prop="balance" />
      <el-table-column label="实际收入" align="center" prop="actualIncome" />
      <el-table-column label="盘盈盘亏" align="center" prop="profit" />
      <el-table-column label="盘注" align="center" prop="remarks" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['shop:monthIncome:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['shop:monthIncome:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改利润月结对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="monthIncomeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="盘点年份" prop="year"  >
          <el-input v-model="form.year" placeholder="请输入盘点年份" @change="getData" />
        </el-form-item>
        <el-form-item label="盘点月份" prop="month"  >
          <el-select v-model="form.month" placeholder="请选择盘点月份" @change="getData">
            <el-option
              v-for="dict in shop_inventory_month"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品" prop="status">
          <el-select v-model="form.fid" placeholder="请选择商品" clearable   @change="getData">
            <el-option
                v-for="item in  fGroup"
                :key="item.fid"
                :label="item.food"
                :value="item.fid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="本月开销" prop="purchaseIncome">
          <el-input v-model="form.purchaseIncome" placeholder="请输入本月开销" disabled/>
        </el-form-item>
        <el-form-item label="本月收入" prop="sellIncome">
          <el-input v-model="form.sellIncome" placeholder="请输入本月收入" disabled/>
        </el-form-item>
        <el-form-item label="本月利润" prop="balance">
          <el-input v-model="balance" placeholder="" disabled/>
        </el-form-item>
        <el-form-item label="实际收入" prop="actualIncome">
          <el-input v-model="form.actualIncome" placeholder="请输入实际收入" @change="getProfit" />
        </el-form-item>
        <el-form-item label="盘盈盘亏" prop="profit">
          <el-input v-model="form.profit" placeholder="请输入盘盈盘亏" />
        </el-form-item>
        <el-form-item label="盘注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入盘点备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MonthIncome">
import {
  listMonthIncome,
  getMonthIncome,
  delMonthIncome,
  addMonthIncome,
  updateMonthIncome,
  listMonthIncome2
} from "@/api/shop/monthIncome";
import {listFood} from "@/api/shop/food";
import {listDayIncome} from "@/api/shop/dayIncome";

const { proxy } = getCurrentInstance();
const { shop_inventory_month } = proxy.useDict('shop_inventory_month');

const monthIncomeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const balance = ref();
const title = ref("");
const fGroup = ref([]);
const oData = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    year: null,
    month: null,
    fid: null,
  },
  inventoryParams:{
    year:null,
    month:null,
    fid:null,
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    year: [
      { required: true, message: "盘点年份不能为空", trigger: "blur" }
    ],
    month: [
      { required: true, message: "盘点月份不能为空", trigger: "change" }
    ],
    fid: [
      { required: true, message: "商品ID不能为空", trigger: "blur" }
    ],
    purchaseIncome: [
      { required: true, message: "本月开销不能为空", trigger: "blur" }
    ],
    sellIncome: [
      { required: true, message: "本月收入不能为空", trigger: "blur" }
    ],
    actualIncome: [
      { required: true, message: "实际收入不能为空", trigger: "blur" }
    ],
    profit: [
      { required: true, message: "盘盈盘亏不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules,inventoryParams } = toRefs(data);

/** 查询利润月结列表 */
function getList() {
  loading.value = true;
  listMonthIncome(queryParams.value).then(response => {
    monthIncomeList.value = response.rows.map(item => {
      const balance = parseFloat(item.sellIncome)-parseFloat(item.purchaseIncome)
      return { ...item, balance}
    })
    console.log( monthIncomeList.value)
    loading.value = false

  })
}

function getData(){

  inventoryParams.value.fid=form.value.fid;
  inventoryParams.value.month=form.value.month;
  inventoryParams.value.year=parseFloat(form.value.year);
  if (inventoryParams.value.fid!=null){

    form.value.purchaseIncome=null
    form.value.sellIncome=null

    listMonthIncome2(inventoryParams.value).then(response => {
      oData.value=response.rows;
      form.value.purchaseIncome=oData.value[0].purchaseIncome
      form.value.sellIncome=oData.value[0].sellIncome
      balance.value=parseFloat(form.value.sellIncome)-parseFloat(form.value.purchaseIncome)
    });
  }

}

function getProfit(){
  if (form.value.actualIncome!=null){
    console.log(form.value.sellIncome,form.value.purchaseIncome,form.value.actualIncome)
    form.value.profit=parseFloat(form.value.actualIncome)+parseFloat(form.value.purchaseIncome)-parseFloat(form.value.sellIncome)
  }
}

function getGoods(){
  loading.value = true;
  listFood().then(response =>{
    fGroup.value=response.rows;
  })
  loading.value = false;
}


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  balance.value=null
  form.value = {
    id: null,
    year: null,
    month: null,
    fid: null,
    purchaseIncome: null,
    sellIncome: null,
    actualIncome: null,
    profit: null,
    remarks: null
  };
  oData.value=null
  proxy.resetForm("monthIncomeRef");
}



/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.fid=null
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加利润月结";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getMonthIncome(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改利润月结";
    balance.value=parseFloat(form.value.sellIncome)-parseFloat(form.value.purchaseIncome)
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["monthIncomeRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMonthIncome(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMonthIncome(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除利润月结编号为"' + _ids + '"的数据项？').then(function() {
    return delMonthIncome(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('shop/monthIncome/export', {
    ...queryParams.value
  }, `monthIncome_${new Date().getTime()}.xlsx`)
}
getGoods()
getList();

</script>
